package com.zc.manager.rule.engine.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.StringUtils;
import com.zc.manager.device.service.IIotDeviceService;
import com.zc.manager.rule.engine.domain.IotJob;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 定时任务调度测试
 * 
 */
@Component
public class IotTask {

    @Resource
    private IIotDeviceService iotDeviceService;

    public void invokeTarget(IotJob iotJob) {
        String invokeTargetString = iotJob.getInvokeTarget();

        if (StringUtils.isEmpty(invokeTargetString)) {
            return;
        }

        JSONObject invokeTargetJson = JSON.parseObject(invokeTargetString);

        if (invokeTargetJson == null) {
            return;
        }

        JSONObject properties = invokeTargetJson.getJSONObject("properties");
        doExecutePropertiesDataSend(properties);

        JSONObject functions = invokeTargetJson.getJSONObject("functions");
        doExecuteFunctionsDataSend(functions);
    }

    /**
     * 执行属性数据发送
     * @param data 绑定的属性数据
     */
    private void doExecutePropertiesDataSend(JSONObject data) {
        if (data == null) {
            return;
        }

        data.forEach((productId, devices) -> {
            ((JSONObject)devices).forEach((deviceId, properties) -> {
                ((JSONObject)properties).forEach((propertyId, param) -> {
                    JSONObject paramJson = (JSONObject)param;
                    Map<String, Object> headers = new HashMap<>();

                    if (paramJson == null) {
                        return;
                    }

                    headers.put("sendAndForget", paramJson.getBooleanValue("sendAndForget"));
                    headers.put("ignoreLog", paramJson.getBooleanValue("ignoreLog"));

                    String type = paramJson.getString("type");

                    if ("get".equals(type)) {
                        iotDeviceService
                                .getProperty(deviceId, propertyId, headers)
                                .subscribe();
                        return;
                    }

                    if ("set".equals(type)) {
                        Object value = paramJson.get("value");
                        Map<String, Object> props = new HashMap<>();
                        props.put(propertyId, value);
                        iotDeviceService
                                .writeProperties(deviceId, props, headers)
                                .subscribe();
                    }

                });
            });
        });


    }

    /**
     * 执行功能数据发送
     * @param data 绑定的功能数据
     */
    private void doExecuteFunctionsDataSend(JSONObject data) {
        // TODO
    }
}
